<script lang="ts" setup>
import {ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {FileToBase64} from "../utils"

const
    myPic1 = defineProps({
      picUrl: {//图片地址
        type: [String, Array<String>],
        default: ''
      },
      openDialog: {//是否打开模态框
        type: Boolean,
        default: false
      },
      fileMultiple: {//是否多选
        type: Boolean,
        default: false
      }
    }),
    myPic = ref(),
    $emit = defineEmits(["myPicFile",'deleteChange']),
    imgUrl = ref(),
    imgUrlArr = ref<string | Array<string>>(),
    imgAndSelect = ref(false),
    showImageViewer = ref(false), //组件是否显示
    showImgIndex = ref(0),
    imgFile = ref(),
    key = ref(1)
;

/**
 * 方法定义
 */
const
    selectImage = () => {
      imgFile.value.click()
      key.value++
    },
    handleFileInput = async(event: any) => {
      const files = [...event.target.files]
      if (myPic1.fileMultiple) {
        let fileArr = []
        let fileLength = files.length
        if (imgUrlArr.value?.length === 6) {
          ElMessage({
            message: '最多只能有6张图片',
            type: 'warning',
            duration: 1500
          })
          return
        }
        if (fileLength + imgUrlArr.value?.length > 6) {
          //@ts-ignore
          fileLength = 6 - imgUrlArr.value.length
          ElMessage({
            message: '最多只能有6张图片',
            type: 'warning',
            duration: 1500
          })
        }
        // console.log(files)
        for (let i = 0; i < fileLength; i++) {
          const file = files[i];
          fileArr.push(file)
          const url = await FileToBase64(file)
          imgUrlArr.value = [...imgUrlArr.value as Array<string>, url]
        }
        $emit("myPicFile", {fileArr, url: imgUrl.value,urlArr:imgUrlArr.value})
      } else {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.onload = (e: any) => {
          imgUrl.value = e.target.result
          imgUrlArr.value = [e.target.result]
          imgAndSelect.value = true
          $emit("myPicFile", file)
        };
        reader.readAsDataURL(file);
      }

    },
    showImg = (index = 0) => { //预览大图
      showImgIndex.value = index
      showImageViewer.value = true
    },
    close = () => { //必须要这个事件 不然点击右上角关闭按钮没有反应
      showImageViewer.value = false
    },
    DeleteImg = () => {
      imgUrl.value = ''
      imgUrlArr.value = []
      imgAndSelect.value = false
      $emit('deleteChange',{url: imgUrl.value,urlArr:imgUrlArr.value})
    },
    DeleteImg_Mul = (index: number) => {
      let temp1 = [...imgUrlArr.value as Array<string>]
      let temp2 = [...imgUrl.value]
      temp1.splice(index, 1)
      temp2.splice(index, 1)
      imgUrlArr.value = temp1
      imgUrl.value = temp2
      $emit('deleteChange',{url: imgUrl.value,urlArr:imgUrlArr.value})
    }
;
watch(() => myPic1.openDialog, (newData, oldData) => {
  if (newData || oldData === undefined) {
    myPic.value = myPic1.picUrl
    if (Array.isArray(myPic.value) && myPic.value.length > 0) {
      imgUrl.value = myPic.value
      imgUrlArr.value = myPic.value
    } else if (Array.isArray(myPic.value) && myPic.value.length == 0) {
      imgUrl.value = ''
      imgUrlArr.value = []
    } else {
      imgUrl.value = myPic.value
      imgUrlArr.value = [myPic.value]
    }

    imgAndSelect.value = !!imgUrl.value
  }

}, {immediate: true})
</script>
<template>
  <div v-show="!imgAndSelect && !fileMultiple" class="pic" @click="selectImage">
    <el-icon class="pic_icon" size="30">
      <Picture/>
    </el-icon>
    <span class="pic_text">选择图片</span>
  </div>
  <div v-if="imgAndSelect && !fileMultiple" class="img">
    <el-image :initial-index="4" :max-scale="7" :min-scale="0.2" :src="imgUrl" :zoom-rate="1.2"
              fit="cover" style="width: 120px; height: 120px"/>
    <div class="dark">
      <el-icon class="icon" @click="showImg()">
        <ZoomIn/>
      </el-icon>
      <el-icon class="icon" @click="DeleteImg">
        <Delete/>
      </el-icon>
    </div>
  </div>
  <div v-if="fileMultiple" class="imgMultiple">
    <div v-for="(img, index) in imgUrlArr" :key="index" class="imgMul">
      <el-icon class="imgMulIcon" @click="DeleteImg_Mul(index)">
        <Close/>
      </el-icon>
      <el-image :initial-index="4" :max-scale="7" :min-scale="0.2" :src="img"
                :zoom-rate="1.2" fit="cover" style="width: 120px; height: 120px;border-radius: 5px;"
                @click="showImg(index)"/>
    </div>
    <div v-show="(imgUrlArr?.length as number) < 6" class="pic" @click="selectImage">
      <el-icon class="pic_icon" size="30">
        <Picture/>
      </el-icon>
      <span class="pic_text">选择图片</span>
    </div>
  </div>
  <el-image-viewer v-if="showImageViewer" :initial-index="showImgIndex" :url-list="(imgUrlArr as Array<string>)"
                   @close="close"></el-image-viewer>
  <input :key="key" ref="imgFile" :multiple="fileMultiple" style="display: none;" type="file"
         @change="handleFileInput"/>
</template>
<style lang="scss" scoped>
.pic {
  user-select: none;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  background-color: #eff0f2;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    color: #4165d7;
  }
}

.img {
  width: 120px;
  height: 120px;
  border-radius: 5px;
  position: relative;
  overflow: hidden;

  .dark {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    position: absolute;
    top: 0;

    .icon {
      margin: 0 10px;
      font-size: 20px;
      color: #ffffff;
      display: none;

    }

    &:hover {
      background-color: rgba(0, 0, 0, 0.5);
    }

    &:hover .icon {
      display: block;
    }
  }
}

.imgMultiple {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;

  .imgMul {
    width: 120px;
    height: 120px;
    // overflow: hidden;
    border-radius: 5px;
    margin-right: 10px;
    margin-bottom: 10px;
    position: relative;

    .imgMulIcon {
      width: 15px;
      height: 15px;
      box-sizing: border-box;
      padding: 2px;
      position: absolute;
      top: -4px;
      right: -4px;
      font-size: 20px;
      z-index: 99;
      color: #ffffff;
      cursor: pointer;
      background-color: #d8d2d2;
      border-radius: 50%;
    }
  }
}
</style>
